import { BadRequestException, Injectable } from '@nestjs/common';
import { CreateRecordDto } from './dto/create-record.dto';
import { UpdateRecordDto } from './dto/update-record.dto';
import { CrudService } from '../../common/crud/crud.service';
import { PrismaService } from 'nestjs-prisma';

@Injectable()
export class RecordService extends CrudService {
  constructor(readonly prisma: PrismaService) {
    super(prisma, 'record');
  }
  async getProcessCount(sizeId: string, styleId: string, index: number) {
    const history = await this.prisma.record.findMany({
      where: {
        sizeId: sizeId,
        styleId: styleId,
        processIndex: index
      },
    });

    let count = 0;
    history.forEach((item) => {
      count += item.number;
    });

    return count;
  }

  async getAmount(styleId: string, sizeId: string) {
    const styleOnSize = await this.prisma.styleOnSize.findUnique({
      where: {
        styleId_sizeId: {
          styleId: styleId,
          sizeId: sizeId,
        },
      },
    });

    if (!styleOnSize) {
      throw new BadRequestException('未找到相关款式和尺寸');
    }
    return styleOnSize.amount;
  }

  async create(createRecordDto: CreateRecordDto, userId: string) {
    const amount = await this.getAmount(
      createRecordDto.styleId,
      createRecordDto.sizeId,
    );
    const currentProcess = await this.prisma.process.findUnique({
      where: {
        id: createRecordDto.processId
      }
    })
    let count = await this.getProcessCount(
      createRecordDto.sizeId,
      createRecordDto.styleId,
      currentProcess.index,
    );

    console.log(count, createRecordDto.number, amount);
    if (count + createRecordDto.number > amount) {
      throw new BadRequestException(
        `超出当前工序上限,当前${count}/${amount},剩余${amount - count}`,
      );
    }



    return this.prisma.record.create({
      data: {
        userId: userId,
        workerId: createRecordDto.workerId,
        processIndex: currentProcess.index,
        description: createRecordDto.description,
        date: createRecordDto.date,
        sizeId: createRecordDto.sizeId,
        number: createRecordDto.number,
        styleId: createRecordDto.styleId,
      },
    });
  }

  async update(id: string, updateRecordDto: UpdateRecordDto) {
    const current = await this.prisma.record.findUnique({
      where: {
        id: id,
      },
    });


    const amount = await this.getAmount(current.styleId, current.sizeId);

    let count = await this.getProcessCount(
      current.sizeId,
      current.styleId,
      current.processIndex,
    );

    if (count - current.number + updateRecordDto.number > amount) {
      throw new BadRequestException(
        `超出当前工序上限,当前${count - current.number}/${amount},剩余${amount - (count - current.number)}`,
      );
    }

    return this.prisma.record.update({
      where: {
        id,
      },
      data: {
        number: updateRecordDto.number,
      },
    });
  }
}
